package com.signway.swmediaplayerdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.signway.SignwayManager;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.signway.swmediaplayer.SWMediaPlayer;
import com.signway.swmediaplayer.utils.SystemProperties;
import com.signway.swmediaplayerdemo.databinding.ActivityMainBinding;
import com.signway.swmediaplayerdemo.test.Text;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getName();
    private ActivityMainBinding binding;

    private SignwayManager sm;
    private AudioManager mAudioManager = null;

    private static final int REQUEST_CODE = 0;
    public static TestMode mTestMode;
    public static TestRes mTestRes;

    public enum TestMode {
        FULL_CONTINUE, /* 无缝零时差-视频格式与布局保持一致 */
        FULL_VIDEO_IMAGE,/* 视频切图片-图片完全遮挡视频，前后视频格式与布局保持一致 */
        FULL_VIDEO_RESET,/* 视频格式发送变化-布局一致 */
        SPLIT_CONTINUE, /* 无缝零时差-视频格式与布局保持一致 */
        SPLIT_VIDEO_RESET,/* 视频格式发送变化-布局一致 */
        VIDEO_LAYOUT,/* 视频格式与视频布局发送变化 */
        FULL_IMAGE,/* 全屏图片带PQ */
    };

    public enum TestRes {
        NOTHING,/* 全屏切换分屏 */
        FULL_SCREEN_2K,/* 全屏模式 */
        FULL_SCREEN_2K_H,/* 全屏模式 */
        FULL_SCREEN_4K,/* 全屏模式 */
        FULL_SCREEN_4K_H,/* 全屏模式 */
        FULL_SCREEN_4K_ROTATION,/* 全屏模式 */
        SPLIT_SCREEN,/* 分屏模式 */
    };

    private static final int SELECT_MODE = 0;
    private static final int SELECT_RES = 1;
    private int mCurStatus = SELECT_MODE;

    @SuppressLint({"NonConstantResourceId", "SdCardPath"})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.permission:
                requestPermission();
                break;
            case R.id.media_player_full_continue:
                mTestMode = TestMode.FULL_CONTINUE;
                binding.playerModeLayout.setVisibility(View.GONE);
                binding.playerResLayout.setVisibility(View.VISIBLE);
                mCurStatus = SELECT_RES;
                break;
            case R.id.media_player_full_reset:
                mTestMode = TestMode.FULL_VIDEO_RESET;
                binding.playerModeLayout.setVisibility(View.GONE);
                binding.playerResLayout.setVisibility(View.VISIBLE);
                mCurStatus = SELECT_RES;
                break;
            case R.id.media_player_full_image:
                mTestMode = TestMode.FULL_VIDEO_IMAGE;
                binding.playerModeLayout.setVisibility(View.GONE);
                binding.playerResLayout.setVisibility(View.VISIBLE);
                mCurStatus = SELECT_RES;
                break;
            case R.id.media_player_split_continue:
                mTestMode = TestMode.SPLIT_CONTINUE;
                binding.playerModeLayout.setVisibility(View.GONE);
                binding.playerResLayout.setVisibility(View.VISIBLE);
                mCurStatus = SELECT_RES;
                break;
            case R.id.media_player_split_reset:
                mTestMode = TestMode.SPLIT_VIDEO_RESET;
                binding.playerModeLayout.setVisibility(View.GONE);
                binding.playerResLayout.setVisibility(View.VISIBLE);
                mCurStatus = SELECT_RES;
                break;
            case R.id.media_player_split_layout: {
                Intent intent = new Intent(MainActivity.this, ListSwitchDoubleActivity.class);
                startActivity(intent);
            } break;
            case R.id.media_4k:
                mTestRes = TestRes.FULL_SCREEN_4K;
                break;
            case R.id.media_2k:
                mTestRes = TestRes.FULL_SCREEN_2K;
                break;
            case R.id.media_4k_h:
                mTestRes = TestRes.FULL_SCREEN_4K_H;
                break;
            case R.id.media_2k_h:
                mTestRes = TestRes.FULL_SCREEN_2K_H;
                break;
            case R.id.media_4k_rotation:
                mTestRes = TestRes.FULL_SCREEN_4K_ROTATION;
                break;
            case R.id.test_start:
                testStart();
                break;
            case R.id.full_image: {
                Intent intent = new Intent(MainActivity.this, ImageActivity.class);
                startActivity(intent);
            } break;
            case R.id.subtitle: {
                Intent intent = new Intent(MainActivity.this, SubtitleActivity.class);
                startActivity(intent);
            } break;
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        sm = getSystemService(SignwayManager.class);
        sm.setSystemAppMode(0);
        sm.setAudioMute(false);
        sm.setAudioVolume(sm.getAudioMaxVolume());
//        sm.setAudioVolume(sm.getAudioMaxVolume() / 2);
        sm.setMcuWatchDog(false);
        binding.playerVersion.setText("Ver:" + sm.getPlayerVersion());

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);

        hideBottomUIMenu(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPathListIndex = 0;
        binding.playerModeLayout.setVisibility(View.VISIBLE);
        binding.playerResLayout.setVisibility(View.GONE);
        mCurStatus = SELECT_MODE;
        SystemProperties.setProp("vendor.mstar.mmvideo.keep-lastframe", "false");
    }

    @Override
    public void onBackPressed() {
        if (mCurStatus == SELECT_RES) {
            binding.playerModeLayout.setVisibility(View.VISIBLE);
            binding.playerResLayout.setVisibility(View.GONE);
            mCurStatus = SELECT_MODE;
        } else {
            super.onBackPressed();
        }
    }

    private void testStart() {
        switch (mTestRes) {
            case FULL_SCREEN_2K:
                videoPathList = new String[] {
//                        Environment.getExternalStorageDirectory().getPath() + "/001.mp4",
//                        Environment.getExternalStorageDirectory().getPath() + "/002.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/2_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/3_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/4_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/5_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/6_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/7_v_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp5_mp3/9_v_25_8px_1080.mp4",
                };
                break;
            case FULL_SCREEN_4K:
                videoPathList = new String[] {
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/2_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/3_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/4_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/5_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/6_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/7_v_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp4/9_v_25_8px.mp4",
                };
            break;
            case FULL_SCREEN_2K_H:
                videoPathList = new String[] {
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/2_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/3_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/4_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/5_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/6_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/7_h_25_1080.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp9/9_h_25_8px_1080.mp4",
                };
                break;
            case FULL_SCREEN_4K_H:
                videoPathList = new String[] {
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/2_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/3_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/4_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/5_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/6_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/7_h_25.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp8/9_h_25_8px.mp4",
                };
                break;
            case FULL_SCREEN_4K_ROTATION:
                videoPathList = new String[] {
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/2_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/3_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/4_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/5_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/6_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/7_h_25_r90.mp4",
                        Environment.getExternalStorageDirectory().getPath() + "/testmp6/9_h_25_8px_r90.mp4",
                };
            break;
        }

        switch (mTestMode) {
            case FULL_CONTINUE: {
                Intent intent = new Intent(MainActivity.this, MediaActivity.class);
                intent.putExtra("MODE", SWMediaPlayer.MEDIA_COMPLETION_CONTINUE);
                startActivity(intent);
            } break;
            case SPLIT_CONTINUE: {
                Intent intent = new Intent(MainActivity.this, SplitActivity.class);
                intent.putExtra("MODE", SWMediaPlayer.MEDIA_COMPLETION_CONTINUE);
                startActivity(intent);
            } break;
            case FULL_VIDEO_IMAGE: {
                Intent intent = new Intent(MainActivity.this, MediaActivity.class);
                intent.putExtra("MODE", SWMediaPlayer.MEDIA_COMPLETION_PAUSE);
                startActivity(intent);
            } break;
            case FULL_VIDEO_RESET: {
                Intent intent = new Intent(MainActivity.this, MediaActivity.class);
                intent.putExtra("MODE", SWMediaPlayer.MEDIA_COMPLETION_STOP);
                startActivity(intent);
            } break;
        }

    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    public static void hideBottomUIMenu(Activity activity) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.INVISIBLE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View .SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_LONG).show();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE);
            }
        } else {
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_LONG).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
            }
        }
    }

    public static final int VIDEO = 0;
    public static final int IMAGE = 1;
    public static class VideoRes {
        int type;
        int width;
        int height;
        String path;
    }

    private static int videoPathListIndex = 0;
    private static String videoPathList[] = null;
    public static VideoRes getVideoPath() {
        VideoRes res = new VideoRes();
        res.path = videoPathList[videoPathListIndex++];
        if (videoPathListIndex >= videoPathList.length) {
            videoPathListIndex = 0;
        }
        if (res.path.toLowerCase().endsWith(".mp4")) {
            res.type = VIDEO;
            if (res.path.endsWith("_1080.mp4")) {
                res.width = 1080;
                res.height = 1920;
            }
        } else {
            res.type = IMAGE;
        }
        return res;
    }

    public static String[] getVideoPathList() {
        return videoPathList;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_LONG).show();
            }
        }
    }
}